/**
 * C Implementation: grib_multi_write
 *
 * Description:
 *  How to encode GRIB2 messages containing multiple fields
 *  如何编码包含多个字段的 GRIB2 消息
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "eccodes.h"

static void usage(const char* prog)
{
    printf("usage: %s in.grib out.grib\n", prog);
    exit(1);
}

int sfx_grib_multi_write()
{
    int err  = 0;
    FILE* in = NULL;
    FILE* of = NULL;
    long edition, step;
    const int start_section = 4;  // Grib2 Product Definition Section

    char* filename  = "d:/sfxData/ECMWF/eccodes_test_data/multi.grib2";
    char* ofilename = "d:/temp/out.grib";

    // open input file
    in = fopen(filename, "rb");

    // new grib handle from input file
    codes_handle* h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err);
    CODES_CHECK(err, 0);
    CODES_CHECK(codes_get_long(h, "edition", &edition), 0);  //
    assert(edition == 2);
    printf("Input grib must be edition 2 for multi fields\n");

    // create a new empty multi field handle
    codes_multi_handle* mh = codes_grib_multi_handle_new(0);

    for (step = 12; step <= 120; step += 12) {
        // 
        // set step 
        codes_set_long(h, "step", step);
        // append h to mh repeating from section 4 
        // i.e. starting from section 4 all the sections to the end of the message will be copied 
        codes_grib_multi_handle_append(h, start_section, mh);
    }

    // open output file 
    of = fopen(ofilename, "wb");

    // write multi fields handle to output file 
    codes_grib_multi_handle_write(mh, of);
    fclose(of);

    // free memory
    codes_grib_multi_handle_delete(mh);
    codes_handle_delete(h);
    fclose(in);
    return 0;
}

